<template>
    <div class="project-management">
      <!-- 头部区域 -->
      <div class="title-container">
        <div class="left">
          <i class="el-icon-folder-opened"></i>
          <span>项目管理</span>
        </div>
        <div class="right">
          <el-button type="primary" @click="handleAddProject">
            <i class="el-icon-plus"></i> 新增项目
          </el-button>
        </div>
      </div>
  
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-card>
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="项目名称">
              <el-input v-model="searchForm.name" placeholder="请输入项目名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="项目状态">
              <el-select v-model="searchForm.status" placeholder="请选择" clearable>
                <el-option label="草稿" value="draft"></el-option>
                <el-option label="已发布" value="published"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="收费类型">
              <el-select v-model="searchForm.isFree" placeholder="请选择" clearable>
                <el-option label="免费" :value="true"></el-option>
                <el-option label="收费" :value="false"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetSearchForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
  
      <!-- 主体内容区 -->
      <div class="project-table-container">
        <el-card>
          <el-table
            :data="projects"
            border
            style="width: 100%"
            v-loading="loading">
            <el-table-column prop="id" label="ID" width="80"/>
            <el-table-column prop="name" label="项目名称" width="180"/>
            <el-table-column prop="category" label="分类" width="120"/>
            <el-table-column label="收费类型" width="100">
              <template slot-scope="scope">
                {{ scope.row.isFree ? '免费' : '收费' }}
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" width="100">
              <template slot-scope="scope">
                {{ scope.row.isFree ? '0.00' : scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="downloadCount" label="下载次数" width="100"/>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === 'published' ? 'success' : 'info'">
                  {{ scope.row.status === 'published' ? '已发布' : '草稿' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="280" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="handleEditProject(scope.row)">
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  type="success"
                  icon="el-icon-view"
                  @click="handleViewScreenshots(scope.row)"
                  v-if="scope.row.screenshots && scope.row.screenshots.length > 0">
                  查看截图
                </el-button>
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-upload2"
                  @click="handlePublish(scope.row)"
                  v-if="scope.row.status !== 'published'">
                  发布
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleDeleteProject(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
  
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </el-card>
      </div>
  
      <!-- 项目表单对话框 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        :modal="true"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
        :append-to-body="true"
        custom-class="feedback-dialog"
        width="650px">
        <el-form
          :model="projectForm"
          :rules="rules"
          ref="projectForm"
          label-width="120px">
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="projectForm.name"/>
          </el-form-item>
          <el-form-item label="项目分类" prop="categoryId">
            <el-select v-model="projectForm.categoryId" placeholder="请选择分类">
              <el-option
                v-for="item in categories"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目标签">
            <el-select
              v-model="projectForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择标签">
              <el-option
                v-for="item in tags"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否免费" prop="isFree">
            <el-switch v-model="projectForm.isFree"></el-switch>
          </el-form-item>
          <el-form-item label="价格" prop="price" v-if="!projectForm.isFree">
            <el-input-number v-model="projectForm.price" :min="0" :step="1" step-strictly></el-input-number>
          </el-form-item>
          <el-form-item label="项目描述" prop="description">
            <el-input
              type="textarea"
              v-model="projectForm.description"
              :rows="3"/>
          </el-form-item>
          <el-form-item label="使用Gitee托管" prop="useGitee">
            <el-switch v-model="projectForm.useGitee"></el-switch>
          </el-form-item>
          <el-form-item label="项目文件" prop="filePath" v-if="dialogType === 'add'">
            <div v-if="!projectForm.useGitee">
              <el-upload
                class="project-file-uploader"
                :action="`/api/system/projects/upload`"
                :headers="uploadHeaders"
                :on-success="handleFileSuccess"
                :on-error="handleFileError"
                :before-upload="beforeFileUpload"
                :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传zip/rar文件，且不超过100MB</div>
              </el-upload>
            </div>
            <div v-else>
              <div v-if="!giteeRepoCreated">
                <el-button type="primary" @click="createGiteeRepo" :loading="creatingRepo">创建Gitee仓库</el-button>
                <div v-if="creatingRepoError" class="error-message">{{ creatingRepoError }}</div>
              </div>
              <div v-else>
                <p>Gitee仓库创建成功</p>
                <p>仓库名: {{ giteeRepoInfo.repoName }}</p>
                <p>Web地址: <a :href="giteeRepoInfo.webUrl" target="_blank">{{ giteeRepoInfo.webUrl }}</a></p>
                
                <div class="manual-upload">
                  <input 
                    type="file" 
                    ref="giteeFileInput" 
                    @change="giteeFileSelected" 
                    style="display: none"
                  >
                  <el-button 
                    size="small" 
                    type="primary" 
                    @click="triggerGiteeFileSelect"
                    :loading="uploadingToGitee"
                  >
                    选择文件上传到Gitee
                  </el-button>
                  <span v-if="selectedGiteeFile" class="selected-file">
                    已选择: {{ selectedGiteeFile.name }}
                  </span>
                  <div class="el-upload__tip">文件将上传到Gitee仓库</div>
                  
                  <div v-if="giteeUploadProgress > 0 && giteeUploadProgress < 100" class="upload-progress">
                    <el-progress :percentage="giteeUploadProgress"></el-progress>
                  </div>
                  <div v-if="giteeUploadError" class="upload-error">
                    {{ giteeUploadError }}
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="项目截图">
            <div>
              <el-upload
                class="project-screenshot-uploader"
                :action="`/api/test/images/upload`"
                :headers="uploadHeaders"
                list-type="picture-card"
                :file-list="screenshotFileList"
                :on-success="handleScreenshotSuccess"
                :on-error="handleFileError"
                :before-upload="beforeScreenshotUpload">
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>
            
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitProject">确 定</el-button>
        </div>
      </el-dialog>
  
      <!-- 截图预览对话框 -->
      <el-dialog
        title="项目截图"
        :visible.sync="screenshotDialogVisible"
        custom-class="feedback-dialog">
        <div class="screenshot-container">
          <el-carousel :interval="4000" type="card" height="400px">
            <el-carousel-item v-for="(item, index) in currentScreenshots" :key="index">
              <img :src="fileDownloadUrl + item.path" class="screenshot-image" />
            </el-carousel-item>
          </el-carousel>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import axios from 'axios'
  
  export default {
    name: 'ProjectManagement',
    data() {
      return {
        // 项目列表数据
        projects: [],
        loading: false,
        page: 1,
        pageSize: 10,
        total: 0,
        
        // 搜索表单
        searchForm: {
          name: '',
          status: '',
          isFree: ''
        },
        
        // 对话框控制
        dialogVisible: false,
        dialogTitle: '新增项目',
        dialogType: 'add',
        
        // 项目表单
        projectForm: {
          name: '',
          categoryId: '',
          tags: [],
          isFree: true,
          price: 0,
          description: '',
          filePath: '',
          screenshots: [],
          useGitee: false,
          giteeRepoName: '',
          giteeRepoUrl: '',
          giteeDownloadUrl: ''
        },
        
        // 表单规则
        rules: {
          name: [
            { required: true, message: '请输入项目名称', trigger: 'blur' }
          ],
          categoryId: [
            { required: true, message: '请选择项目分类', trigger: 'change' }
          ],
          description: [
            { required: true, message: '请输入项目描述', trigger: 'blur' }
          ],
          // filePath: [
          //   { required: true, message: '请上传项目文件', trigger: 'change' }
          // ],
          price: [
            { required: true, message: '请输入项目价格', trigger: 'blur' }
          ]
        },
        
        // 分类和标签数据
        categories: [],
        tags: [],
        
        // 文件上传
        fileList: [],
        screenshotFileList: [],
        uploadHeaders: {
          Authorization: localStorage.getItem('token')
        },
        
        // 截图预览
        screenshotDialogVisible: false,
        currentScreenshots: [],
        
        // Gitee相关数据
        giteeRepoCreated: false,
        creatingRepo: false,
        creatingRepoError: '',
        giteeRepoInfo: {},
        selectedGiteeFile: null,
        uploadingToGitee: false,
        giteeUploadProgress: 0,
        giteeUploadError: '',
        giteeAccessToken: '',
        
        // Gitee截图相关数据
        giteeScreenshotList: [],
        screenshotUploadProgress: 0,
        uploadingScreenshot: false
      }
    },
    created() {
      this.fetchProjects()
      this.fetchCategories()
      this.fetchTags()
      const accountInfo = JSON.parse(localStorage.getItem('account') || '{}');
      console.log(accountInfo);
    },
    computed: {
      fileDownloadUrl() {
        return 'http://your-server-ip:8080/files/' // 根据实际情况修改
      }
    },
    methods: {
      // 格式化日期
      formatDate(date) {
        if (!date) return '';
        
        if (typeof date === 'string') {
          date = new Date(date);
        }
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
      
      // 获取项目列表
      async fetchProjects() {
        this.loading = true
        try {
          const params = {
            page: this.page,
            size: this.pageSize,
            ...this.searchForm
          }
          
          const res = await axios.get('/api/system/projects', { params })
          if (res.data.code === 200) {
            this.projects = res.data.data
            this.total = res.data.total || res.data.data.length
          } else {
            this.$message.error(res.data.message || '获取项目列表失败')
          }
        } catch (error) {
          console.error('获取项目列表失败', error)
          this.$message.error('获取项目列表失败')
        } finally {
          this.loading = false
        }
      },
      
      // 获取分类列表
      async fetchCategories() {
        try {
          const res = await axios.get('/api/system/projects/categories')
          if (res.data.code === 200) {
            this.categories = res.data.data
          }
        } catch (error) {
          console.error('获取分类列表失败', error)
          this.$message.error('获取分类列表失败')
        }
      },
      
      // 获取标签列表
      async fetchTags() {
        try {
          const res = await axios.get('/api/system/projects/tags')
          if (res.data.code === 200) {
            this.tags = res.data.data
          }
        } catch (error) {
          console.error('获取标签列表失败', error)
          this.$message.error('获取标签列表失败')
        }
      },
      
      // 搜索
      handleSearch() {
        this.page = 1
        this.fetchProjects()
      },
      
      // 重置搜索表单
      resetSearchForm() {
        this.searchForm = {
          name: '',
          status: '',
          isFree: ''
        }
        this.handleSearch()
      },
      
      // 分页处理
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchProjects()
      },
      
      handleCurrentChange(val) {
        this.page = val
        this.fetchProjects()
      },
      
      // 添加项目
      handleAddProject() {
        this.dialogType = 'add'
        this.dialogTitle = '新增项目'
        this.projectForm = {
          name: '',
          categoryId: '',
          tags: [],
          isFree: true,
          price: 0,
          description: '',
          filePath: '',
          screenshots: [],
          useGitee: false,
          giteeRepoName: '',
          giteeRepoUrl: '',
          giteeDownloadUrl: ''
        }
        this.fileList = []
        this.screenshotFileList = []
        this.dialogVisible = true
      },
      
      // 编辑项目
      handleEditProject(row) {
        this.dialogType = 'edit'
        this.dialogTitle = '编辑项目'
        this.projectForm = { ...row }
        
        // 处理标签数据
        if (row.tags && Array.isArray(row.tags)) {
          this.projectForm.tags = row.tags.map(tag => tag.id)
        } else {
          this.projectForm.tags = []
        }
        
        // 处理截图文件列表
        this.screenshotFileList = []
        if (row.screenshots && Array.isArray(row.screenshots)) {
          this.screenshotFileList = row.screenshots.map(screenshot => {
            return {
              name: screenshot.name || '截图',
              url: this.fileDownloadUrl + screenshot.path
            }
          })
        }
        
        this.dialogVisible = true
      },
      
      // 删除项目
      async handleDeleteProject(row) {
        try {
          await this.$confirm('确认删除该项目吗？删除后不可恢复！', '提示', {
            type: 'warning'
          })
          
          const res = await axios.delete(`/api/system/projects/${row.id}`, {
            params: { creatorId: row.creatorId }
          })
          
          if (res.data.code === 200) {
            this.$message.success('删除成功')
            this.fetchProjects()
          } else {
            this.$message.error(res.data.message || '删除失败')
          }
        } catch (error) {
          if (error !== 'cancel') {
            console.error('删除项目失败', error)
            this.$message.error('删除失败')
          }
        }
      },
      
      // 发布项目
      async handlePublish(row) {
        try {
          const res = await axios.post(`/api/system/projects/${row.id}/publish`, null, {
            params: { creatorId: row.creatorId }
          })
          
          if (res.data.code === 200) {
            this.$message.success('项目发布成功')
            this.fetchProjects()
          } else {
            this.$message.error(res.data.message || '发布失败')
          }
        } catch (error) {
          console.error('发布项目失败', error)
          this.$message.error('发布失败')
        }
      },
      
      // 查看截图
      handleViewScreenshots(row) {
        if (row.screenshots && row.screenshots.length > 0) {
          this.currentScreenshots = row.screenshots
          this.screenshotDialogVisible = true
        } else {
          this.$message.info('该项目没有截图')
        }
      },
      
      // 文件上传相关方法
      beforeFileUpload(file) {
        const isZipOrRar = file.type === 'application/zip' || 
                         file.type === 'application/x-rar-compressed' ||
                         file.name.endsWith('.zip') || 
                         file.name.endsWith('.rar')
        const isLt100M = file.size / 1024 / 1024 < 100
        
        if (!isZipOrRar) {
          this.$message.error('请上传zip或rar格式的文件!')
        }
        
        if (!isLt100M) {
          this.$message.error('文件大小不能超过100MB!')
        }
        
        return isZipOrRar && isLt100M
      },
      
      handleFileSuccess(response, file, fileList) {
        if (response.code === 200) {
          this.projectForm.filePath = response.data
          this.$message.success('文件上传成功')
        } else {
          this.$message.error(response.message || '文件上传失败')
        }
      },
      
      beforeScreenshotUpload(file) {
        const isImage = file.type.startsWith('image/')
        const isLt5M = file.size / 1024 / 1024 < 5
        
        if (!isImage) {
          this.$message.error('请上传图片格式的文件!')
        }
        
        if (!isLt5M) {
          this.$message.error('图片大小不能超过5MB!')
        }
        
        return isImage && isLt5M
      },
      
      handleScreenshotSuccess(response, file, fileList) {
        if (response.code === 200) {
          // 保存截图路径
          if (!this.projectForm.screenshots) {
            this.projectForm.screenshots = []
          }
          
          this.projectForm.screenshots.push({
            name: file.name,
            path: response.message
          })
          
          this.$message.success('截图上传成功')
          console.log(this.projectForm.screenshots)
        } else {
          this.$message.error(response.message || '截图上传失败')
        }
      },
      
      handleFileError(err) {
        console.error('文件上传失败', err)
        this.$message.error('文件上传失败')
      },
      
      // 触发文件选择
      triggerGiteeFileSelect() {
        this.$refs.giteeFileInput.click();
      },
      
      // 文件选择处理
      giteeFileSelected(event) {
        const file = event.target.files[0];
        if (!file) return;
        
        this.selectedGiteeFile = file;
        this.uploadToGitee(file);
      },
      
      // 直接上传到Gitee
      async uploadToGitee(file) {
        if (!this.giteeRepoInfo.repoName) {
          this.$message.error('请先创建Gitee仓库');
          return;
        }
        
        this.uploadingToGitee = true;
        this.giteeUploadProgress = 0;
        this.giteeUploadError = '';
        
        try {
          // 准备FormData
          const formData = new FormData();
          formData.append('file', file);
          formData.append('repoName', this.giteeRepoInfo.repoName);
          
          // 发送请求并监控进度
          const response = await axios.post('/api/system/projects/upload-to-gitee', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            },
            onUploadProgress: (progressEvent) => {
              const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
              this.giteeUploadProgress = percentCompleted;
            }
          });
          
          if (response.data.code === 200) {
            this.projectForm.filePath = response.data.data;
            this.projectForm.giteeDownloadUrl = response.data.data;
            this.$message.success('文件上传到Gitee成功');
            this.giteeUploadProgress = 100;
          } else {
            this.giteeUploadError = response.data.message || '上传失败';
            this.$message.error(this.giteeUploadError);
          }
        } catch (error) {
          console.error('上传文件到Gitee失败', error);
          this.giteeUploadError = error.response?.data?.message || error.message || '上传失败';
          this.$message.error('上传文件到Gitee失败: ' + this.giteeUploadError);
        } finally {
          this.uploadingToGitee = false;
        }
      },
      
      // 创建Gitee仓库
      async createGiteeRepo() {
        if (!this.projectForm.name || !this.projectForm.description) {
          this.$message.error('请先填写项目名称和描述');
          return;
        }
        
        this.creatingRepo = true;
        this.creatingRepoError = '';
        
        try {
          const res = await axios.post('/api/system/projects/create-repo', null, {
            params: {
              projectName: this.projectForm.name,
              description: this.projectForm.description
            }
          });
          
          if (res.data.code === 200) {
            this.giteeRepoInfo = res.data.data;
            this.giteeRepoCreated = true;
            this.projectForm.giteeRepoName = this.giteeRepoInfo.repoName;
            this.projectForm.giteeRepoUrl = this.giteeRepoInfo.webUrl;
            this.projectForm.giteeDownloadUrl = this.giteeRepoInfo.downloadUrl;
            this.$message.success('Gitee仓库创建成功');
          } else {
            this.creatingRepoError = res.data.message || '创建Gitee仓库失败';
            this.$message.error(this.creatingRepoError);
          }
        } catch (error) {
          console.error('创建Gitee仓库失败', error);
          this.creatingRepoError = error.message || '创建失败';
          this.$message.error('创建Gitee仓库失败');
        } finally {
          this.creatingRepo = false;
        }
      },
      
      // 触发文件选择对话框
      triggerScreenshotFileInput() {
        if (!this.giteeRepoInfo.repoName) {
          this.$message.warning('请先创建Gitee仓库');
          return;
        }
        this.$refs.screenshotFileInput.click();
      },
      
      // 处理选择的截图文件
      giteeScreenshotSelected(event) {
        const files = event.target.files;
        if (!files || files.length === 0) return;
        
        // 上传单个文件
        this.uploadScreenshotToGitee(files[0]);
        
        // 清空文件输入，允许重复选择同一文件
        event.target.value = null;
      },
      
      // 上传截图到Gitee
      uploadScreenshotToGitee(file) {
        if (!this.giteeRepoInfo.repoName) {
          this.$message.error('请先创建Gitee仓库');
          return;
        }
        
        if (this.uploadingScreenshot) {
          this.$message.warning('正在上传中，请稍候...');
          return;
        }
        
        this.uploadingScreenshot = true;
        this.screenshotUploadProgress = 0;
        
        // 生成唯一文件名，保留原始扩展名
        const originalName = file.name;
        const extension = originalName.includes('.') ? 
            originalName.substring(originalName.lastIndexOf('.')) : '';
        const fileName = `screenshot-${Date.now()}${extension}`;
        
        const formData = new FormData();
        formData.append('file', file);
        formData.append('repoName', this.giteeRepoInfo.repoName);
        formData.append('fileName', fileName);
        
        return axios.post('/api/system/projects/upload-screenshot-to-gitee', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: progressEvent => {
            this.screenshotUploadProgress = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            );
          }
        }).then(response => {
          this.uploadingScreenshot = false;
          
          if (response.data.code === 200) {
            // 修改这里：使用返回的 message 字段作为 URL
            const imageUrl = response.data.message;
            
            // 添加到截图列表
            this.giteeScreenshotList.push({
              name: fileName,
              url: imageUrl
            });
            
            // 更新项目表单中的截图数据
            if (!this.projectForm.screenshots) {
              this.projectForm.screenshots = [];
            }
            
            this.projectForm.screenshots.push({
              name: fileName,
              imagePath: imageUrl  // 使用 Gitee URL
            });
            
            this.$message.success('截图上传成功');
          } else {
            this.$message.error(response.data.message || '截图上传失败');
          }
        }).catch(error => {
          this.uploadingScreenshot = false;
          console.error('上传截图到Gitee失败', error);
          this.$message.error(error.message || '上传异常');
        }).finally(() => {
          // 重置进度
          setTimeout(() => {
            this.screenshotUploadProgress = 0;
          }, 1000);
        });
      },
      
      // 移除Gitee截图
      removeGiteeScreenshot(index) {
        const screenshot = this.giteeScreenshotList[index];
        
        // 从UI列表中移除
        this.giteeScreenshotList.splice(index, 1);
        
        // 从项目表单中移除
        if (this.projectForm.screenshots) {
          const formIndex = this.projectForm.screenshots.findIndex(
            item => item.imagePath === screenshot.url
          );
          
          if (formIndex !== -1) {
            this.projectForm.screenshots.splice(formIndex, 1);
          }
        }
        
        this.$message.success('已移除截图');
        
        // 可选：也可以调用API从Gitee仓库中删除该文件
        // this.deleteGiteeFile(this.giteeRepoInfo.repoName, 'screenshots/' + screenshot.name);
      },
      
      // 可选：从Gitee删除文件
      deleteGiteeFile(repoName, filePath) {
        axios.delete(`/api/system/projects/delete-gitee-file`, {
          params: {
            repoName: repoName,
            filePath: filePath
          }
        }).then(response => {
          if (response.data.code === 200) {
            console.log('文件从Gitee仓库删除成功');
          } else {
            console.warn('从Gitee删除文件失败', response.data.message);
          }
        }).catch(error => {
          console.error('删除Gitee文件请求失败', error);
        });
      },
      
      // 提交项目表单
      async submitProject() {
        try {
          await this.$refs.projectForm.validate();
          
          // Gitee模式验证
          if (this.projectForm.useGitee) {
            if (!this.giteeRepoCreated) {
              this.$message.error('请先创建Gitee仓库');
              return;
            }
            
            // 确保设置了下载地址
            if (!this.projectForm.giteeDownloadUrl) {
              this.projectForm.giteeDownloadUrl = this.giteeRepoInfo.downloadUrl;
            }
            
            // 如果使用Gitee托管，设置文件路径为Gitee下载地址
            this.projectForm.file = {
              fileName: this.giteeRepoInfo.repoName + '.zip',
              filePath: this.projectForm.giteeDownloadUrl,
              fileSize: 0,
              isGitee: true
            };
            
            // 处理Gitee截图路径
            if (this.projectForm.screenshots && this.projectForm.screenshots.length > 0) {
              // 确保所有截图都有完整的 imagePath
              const validScreenshots = this.projectForm.screenshots.filter(screenshot => {
                // 只保留有完整 URL 的截图
                return screenshot.imagePath && typeof screenshot.imagePath === 'string';
              });
              
              // if (validScreenshots.length !== this.projectForm.screenshots.length) {
              //   console.warn('存在无效截图，已过滤');
              //   this.projectForm.screenshots = validScreenshots;
              // }
            }
          } else if (!this.projectForm.file || !this.projectForm.file.filePath) {
            this.$message.error('请上传项目文件');
            return;
          }
          
          // 从localStorage获取用户信息并设置creatorId
          const accountInfo = JSON.parse(localStorage.getItem('account') || '{}');
          if (accountInfo) {
            this.projectForm.creatorId = accountInfo;
          } else {
            this.$message.error('无法获取用户信息，请重新登录');
            return;
          }
          
          // 检查是否有截图但未设置路径
          if (this.projectForm.screenshots && this.projectForm.screenshots.length > 0) {
            const invalidScreenshots = this.projectForm.screenshots.filter(s => !s.imagePath);
            // if (invalidScreenshots.length > 0) {
            //   console.warn('发现没有路径的截图：', invalidScreenshots);
              
            //   // 移除无效截图或设置默认路径
            //   this.projectForm.screenshots = this.projectForm.screenshots.filter(s => s.imagePath);
              
            //   // 如果所有截图都无效，可能需要提示用户
            //   if (this.projectForm.screenshots.length === 0) {
            //     this.$message.warning('所有截图都没有有效路径，将不会保存截图');
            //   }
            // }
          }
          
          // 提交前打印数据，帮助调试
          console.log('提交的项目数据：', JSON.parse(JSON.stringify(this.projectForm)));
          
          // 处理后端API请求
          let res;
          if (this.dialogType === 'add') {
            res = await axios.post('/api/system/projects', this.projectForm);
          } else {
            res = await axios.put(`/api/system/projects/${this.projectForm.id}`, this.projectForm);
          }
          
          if (res.data.code === 200) {
            this.$message.success(this.dialogType === 'add' ? '创建成功' : '更新成功');
            this.dialogVisible = false;
            this.fetchProjects();
          } else {
            this.$message.error(res.data.message || '操作失败');
          }
        } catch (error) {
          console.error('提交项目失败', error);
          this.$message.error(error.response?.data?.message || '提交失败，请检查表单');
        }
      }
    }
  }
  </script>
  
  <style>
  /* 非scoped样式，应用于对话框等 */
  .feedback-dialog {
    background: #fff !important;
  }
  
  .feedback-dialog .el-dialog__header {
    background: #1a237e;
    padding: 20px;
    border-radius: 8px 8px 0 0;
    margin-right: 0;
  }
  
  .feedback-dialog .el-dialog__title {
    color: white;
    font-size: 18px;
    line-height: 24px;
  }
  
  .feedback-dialog .el-dialog__headerbtn {
    top: 15px;
  }
  
  .feedback-dialog .el-dialog__headerbtn .el-dialog__close {
    color: white;
  }
  
  .feedback-dialog .el-dialog__body {
    padding: 30px 20px;
    background: #fff;
  }
  
  .feedback-dialog .el-dialog__footer {
    padding: 15px 20px;
    background: #fff;
    border-radius: 0 0 8px 8px;
  }
  
  /* 遮罩层样式 */
  .v-modal {
    opacity: 0.5 !important;
  }
  </style>
  
  <style scoped>
  .project-management {
    min-height: 100vh;
    background: #f0f2f5;
    padding: 16px;
  }
  
  /* 标题区域样式 */
  .title-container {
    background: #1a237e;
    color: white;
    padding: 16px 24px;
    border-radius: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }
  
  .title-container .left {
    display: flex;
    align-items: center;
    font-size: 18px;
  }
  
  .title-container .left i {
    font-size: 24px;
    margin-right: 8px;
  }
  
  /* 搜索区域样式 */
  .search-container {
    margin-bottom: 16px;
  }
  
  .search-container .el-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }
  
  .search-form {
    padding: 10px 0;
  }
  
  /* 表格区域样式 */
  .project-table-container {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    margin-bottom: 16px;
  }
  
  .project-table-container .el-card {
    border: none;
    margin-bottom: 0;
  }
  
  /* 表格样式 */
  .project-management .el-table th {
    background-color: #1a237e !important;
    color: white !important;
    font-weight: 500;
    padding: 12px 0;
  }
  
  .project-management .el-table td {
    padding: 12px 0;
  }
  
  /* 分页样式 */
  .pagination-container {
    padding: 15px 0;
    text-align: right;
  }
  
  /* 按钮样式 */
  .project-management .el-button--primary {
    background-color: #1a237e;
    border-color: #1a237e;
  }
  
  .project-management .el-button--primary:hover,
  .project-management .el-button--primary:focus {
    background-color: #283593;
    border-color: #283593;
  }
  
  .project-management .el-button--success {
    background-color: #4caf50;
    border-color: #4caf50;
  }
  
  .project-management .el-button--warning {
    background-color: #ff9800;
    border-color: #ff9800;
  }
  
  .project-management .el-button--danger {
    background-color: #f44336;
    border-color: #f44336;
  }
  
  .project-management .el-button--mini {
    border-radius: 4px;
  }
  
  /* 文件上传区域样式 */
  .project-file-uploader {
    width: 100%;
  }
  
  .project-screenshot-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
  }
  
  .project-screenshot-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  
  /* 截图预览样式 */
  .screenshot-container {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .screenshot-image {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
  
  /* 响应式设计 */
  @media screen and (max-width: 768px) {
    .title-container {
      flex-direction: column;
      align-items: flex-start;
    }
    
    .title-container .right {
      margin-top: 10px;
      width: 100%;
    }
    
    .title-container .right .el-button {
      width: 100%;
    }
    
    .search-form {
      display: flex;
      flex-direction: column;
    }
    
    .search-form .el-form-item {
      margin-right: 0;
    }
  }
  
  .manual-upload {
    margin-top: 10px;
  }
  
  .selected-file {
    margin-left: 10px;
    font-size: 14px;
    color: #606266;
  }
  
  .upload-progress {
    margin-top: 10px;
    width: 100%;
  }
  
  .upload-error {
    margin-top: 10px;
    color: #f56c6c;
    font-size: 14px;
  }
  
  .gitee-screenshot-uploader {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .screenshot-uploader-item,
  .screenshot-add-item {
    width: 148px;
    height: 148px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .screenshot-add-item {
    cursor: pointer;
  }
  
  .screenshot-add-item:hover {
    border-color: #409EFF;
  }
  
  .screenshot-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .screenshot-actions {
    position: absolute;
    top: 0;
    right: 0;
    padding: 8px;
    background: rgba(0, 0, 0, 0.5);
    color: white;
    display: none;
  }
  
  .screenshot-uploader-item:hover .screenshot-actions {
    display: block;
  }
  
  .el-icon-delete {
    cursor: pointer;
  }
  
  .el-icon-delete:hover {
    color: #F56C6C;
  }
  </style>